//Configuration
const doc = document;

const author = "com.yin";

//Core
var Assist = {

    "playSpeed": "2",
    "checkDelay": 3000,
    "autoPlay": true,
    "autoClose": true,
    "keepPlaying": true,

    //兼容老版本启动方式
    "start": function(useDefaultConfig) {

        console.log(useDefaultConfig);
        
        if(useDefaultConfig) {

            return Main();
        } else {

            return Main(Assist.playSpeed, Assist.checkDelay, Assist.autoPlay, Assist.autoClose, Assist.keepPlaying);
        }
    },

    "adjustPlaySpeed": function(playSpeedStr) {

        Assist.playSpeed = playSpeedStr;
        log("播放倍速已锁定为: -> " + playSpeedStr + "倍");
    },

    "toggleAutoPlay": function() {

        Assist.autoPlay = !Assist.autoPlay;
        if(Assist.autoPlay) {

            log("AutoPlay 开启");
        } else {

            log("AutoPlay 关闭");
        }
    },

    "toggleAutoClose": function() {

        Assist.autoClose = !Assist.autoClose;
        if(Assist.autoClose) {

            log("AutoClose 开启");
        } else {

            log("AutoClose 关闭");
        }
    },

    "toggleKeepPlaying": function() {

        Assist.keepPlaying = !Assist.keepPlaying;
        if(Assist.keepPlaying) {

            log("KeepPlaying 开启");
        } else {

            log("KeepPlaying 关闭");
        }
    },

    "checkerFunc": function() {

        ++timeCounter;
        checker(doc, Assist.timeCounter, Assist.playSpeed, Assist.autoPlay, Assist.autoClose, Assist.keepPlaying);
    }
};

//------------------两条分割线中间为自定义配置区-----------------------

//播放倍速，默认为1，即正常速度
/**
 * 
 * 在0.8，1，1.2，1.5，2这五个数字随便挑一个填入下面的双引号里
 * 
 */
const playSpeed = "2";//填这里的双引号里面

//每隔多少毫秒检测一次，单位毫秒，1秒=1000毫秒，推荐1000-7000以内，对自己电脑配置自信的可以填1-1000，影响不大
const checkDelay = 3000;//填在左边的等于号右边，分号左边

//视频是否自动开始播放，true为自动开始，false需要手动播放
const autoPlay = true;//填在左边的等于号右边，分号左边

//视频播放结束后是否自动关闭脚本，true为自动关闭，false需要手动关闭
const autoClose = true;//填在左边的等于号右边，分号左边

//确保视频不被暂停，true为确保始终是播放，false为允许手动暂停
const keeyPlaying = true;

//------------------两条分割线中间为自定义配置区-----------------------

//Global variable
var adExists = false;
var timeCounter = 0;
var timerId = -1;
var timerExists = false;

function Main(playSpeed, checkDelay, autoPlay, autoClose, keepPlaying) {

    if(timerExists) return Assist.timerId;

    Assist.playSpeed = playSpeed;
    Assist.checkDelay = checkDelay;
    Assist.autoPlay = autoPlay;
    Assist.autoClose = autoClose;
    Assist.keepPlaying = keepPlaying;

    Assist.timerId = setInterval(Assist.checkerFunc, checkDelay);  
    timerExists = true;

    return Assist.timerId;
}

function Main() {

    if(timerExists) return timerId;

    timer = setInterval(checkerFunc, checkDelay);  
    timerExists = true;

    timerId = timer;

    return timerId;
}

function shouldCloseScript(doc) {

    return getVideoTotalTime(doc) != "00:00" && isElementExists(doc, "div[class='adrPlayBtn']")
        && typeof(getVideoPlayedTime(doc)) != "undefined" && typeof(getVideoTotalTime(doc)) != "undefined";
}

function closeLoop(loop) {

    window.clearInterval(loop);
    timerExists = false;
}

var checkerFunc = function() {

    ++timeCounter;
    checker(doc, timeCounter, playSpeed, autoPlay, autoClose, keeyPlaying);
}

function checker(doc, timeCounter, playSpeed, autoPlay, autoClose, keepPlaying) {   

    log("---------------------------第" + timeCounter + "次检测开始---------------------------");

    //Keep video playing
    var isVideoPlaying = !isElementExists(doc, "div[class='ccH5PlayBtn']");
    if(keepPlaying && !isVideoPlaying) {
        play(doc);
    }

    //AntiAD
    if(!isADExists(doc) && !isElementExists(doc, "div[class='ccH5PlayBtn']")) {

        log("等待广告跳过中...");
        adExists = true;

        //return;
    } else {

        adExists = false;
    }

    if(!adExists) {

        //Make sure video is playing
        if(!isVideoReady(doc)) {

            log("视频未开始播放");
            if(autoPlay) {
                
                log("您已开启了autoPlay，即将将为您自动播放");
                play(doc);
            }
        }

        //Adjust play speed
        var playSpeedCheck = isElementExists(doc, "ul[class='ccH5spul']");
        log("PlaySpeedCheck -- " + playSpeedCheck);
        if(playSpeedCheck) {
            adjustPlaySpeed(doc, playSpeed);
        }

        //Check AFK exists or not
        var AFKCheck = isElementExists(doc, ".check_right_box");
        log("AFKCheck -- " + AFKCheck);
        if(AFKCheck) {
            bypassAntiAFK(doc);
        }

        //Check question area exists or not
        var questionCheck = isElementExists(doc, ".course_point_question_item");
        log("questionCheck -- " + questionCheck);
        if(questionCheck) {
            bypassQuestion(doc);
        }

        log("播放进度: " + getVideoPlayedTime(doc) + "/" + getVideoTotalTime(doc) + "\t" + "当前倍速: " + playSpeed + "倍");
        
        if(autoClose && shouldCloseScript(doc)) {
            closeLoop(timerId);
            log("播放结束，已为您自动结束脚本")
        }
    }

    log("---------------------------第" + timeCounter + "次检测结束---------------------------");
}

function isElementExists(doc, selector) {

    return doc.querySelector(selector) != null;
}

function play(doc) {

    //获取按钮
    var playBtn = doc.querySelector("div[class='ccH5PlayBtn']");

    //模拟点击
    playBtn.click();

    log(playBtn == null ? "开始播放失败" : "开始播放成功");

    if(playBtn != null) {
        playState = true;
    }
}

function pausePlay(doc) {

    //获取按钮
    var pauseBtn = doc.querySelector("span[class='ccH5TogglePause']");

    //模拟点击
    pauseBtn.click();

    log(pauseBtn == null ? "暂停播放失败" : "暂停播放成功");

    if(pauseBtn != null) {
        playState = false;
    }
}

function getVideoPlayedTime(doc) {

    var clazzName = ".ccH5TimeCurrent";

    if(isElementExists(doc, clazzName)) {

        return doc.querySelector(clazzName).innerText;
    } else {

        err("获取当前播放进度失败");
    }
}

function getVideoTotalTime(doc) {

    var clazzName = ".ccH5TimeTotal";

    if(isElementExists(doc, clazzName)) {

        return doc.querySelector(clazzName).innerText;
    } else {

        err("获取总播放进度失败");
    }
}

function isVideoReady(doc) {
    
    var result = getVideoPlayedTime(doc) != undefined;
    return result;
}

function isADExists(doc) {

    return doc.querySelector(".x-advert") == null;
}

function bypassQuestion(doc) {

    //获取答题区li标签
    var skidBtn = doc.getElementsByClassName("course_point_question_item");

    //模拟点击 0为答题结束 1为跳过
    skidBtn[0].click();

    //获取答题区确定按钮
    var okBtn = document.getElementsByClassName("ant-btn ant-btn-primary ant-btn-block");

    //模拟点击
    okBtn[0].click();

    log(skidBtn == null && okBtn == null ? "答题绕过失败" : "答题绕过成功");

}

function bypassAntiAFK(doc) {
    
    //获取继续播放按钮
    var antiAFK = document.querySelector(".check_right_box");

    //模拟点击
    antiAFK.click();

    log(antiAFK == null ? "防挂机绕过失败" : "防挂机绕过成功");

}

function adjustPlaySpeed(doc, playSpeedStr) {

    //获取所有li
    var speed = doc.querySelector("ul[class='ccH5spul']");

    //模拟点击
    speed.children[parsePlaySpeed(playSpeedStr)].click();
}

function parsePlaySpeed(playSpeedStr) {

    if(playSpeedStr == "0.8") {
        return 0;
    }
    if(playSpeedStr == "1") {
        return 1;
    }
    if(playSpeedStr == "1.2") {
        return 2;
    }
    if(playSpeedStr == "1.5") {
        return 3;
    }
    if(playSpeedStr == "2") {
        return 4;
    }

}

function log(msg) {
    console.log("[com.yin / INFO] " + msg);
}

function err(msg) {
    console.error("[com.yin / ERROR] " + msg);
}

//加载完自动启动
Assist.start(false);